package OT.shoufouni.serverThreads;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;

import org.andnav.osm.util.GeoPoint;
import org.andnav.osm.views.overlay.MyLocationOverlay;

import OT.shoufouni.gpsMaps.russionMapExample;
import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.util.Log;

public class serverUpdateMyLocationQuaryThread extends Thread {
	private final russionMapExample callerActivity;
   private final String emailText;
   MyLocationOverlay mLocationOverlay;
   serverUpdateMyLocationQuaryThread(russionMapExample callerActivity, String email, MyLocationOverlay location) {
      this.emailText = email;
      this.mLocationOverlay = location;
      this.callerActivity = callerActivity;
    }
   public void run() {
	   Context context = callerActivity.getApplicationContext();
	   SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
       Boolean keepRuning = prefs.getBoolean("PUSH_LOCATION", false);
	   while (keepRuning){
		   try {
			sleep(10000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		   httpGet(emailText);
		   keepRuning = prefs.getBoolean("PUSH_LOCATION", false);
	   }
   }
   private void httpGet(String srcText) {
	   String requestUrl;
	   StringBuilder builder = new StringBuilder();
	   GeoPoint myLocation = null;
	   myLocation = mLocationOverlay.getMyLocation();
	   if (null==myLocation){
		   // fake point
		   myLocation = new GeoPoint(32.999999,35.000000);
	   }
       try {
    	   double x = (double)myLocation.getLatitudeE6()/1000000;
    	   double y = (double)myLocation.getLongitudeE6()/1000000;
    	   requestUrl = "http://10.0.2.2:8080/serverRestSide2/updateMyLocation/"+srcText+
    	   "/"+x+","+y;
    	   try {
               URL url = new URL(requestUrl.toString());
               BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
               String inputLine = null;
               Log.d("serverUpdateMyLocationQuaryThread ","-----RESPONSE START-----" +" id="+ Thread.currentThread().getId());
               while ((inputLine = in.readLine()) != null) {
            	   builder.append(inputLine);
               }
               in.close();
               Log.d("serverUpdateMyLocationQuaryThread ",builder.toString());
               Log.d("serverUpdateMyLocationQuaryThread ","-----RESPONSE END-----" +" id="+ Thread.currentThread().getId());
               
           } catch (IOException e) {
        	   Log.e("serverUpdateMyLocationQuaryThread ",e.getMessage());
               //e.printStackTrace();
           }
       }finally{
    	   //return builder.toString();
       }
   	}
   
   
}
